package com.ssyc.student.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.ScreenUtils;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.student.R;
import com.ssyc.student.activity.StudentDepotActivity;
import com.ssyc.student.bean.DepotInfo;
import com.ssyc.student.bean.ResultInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端补给站食物列表适配器
 * Created by Administrator on 2018/4/12 0012.
 */

public class StDepotFoodAdapter extends BaseQuickAdapter<DepotInfo.DataBean.Type1Bean, BaseViewHolder> {
    private Context context;
    //屏幕宽度
    private int screenWidth;

    //最外层的布局参数包含图片和按钮
    private RelativeLayout.LayoutParams lpOut;

    //包含ImageView和价格的整体布局参数
    private RelativeLayout.LayoutParams rlLvLp;

    //ImageView的布局参数
    private RelativeLayout.LayoutParams lvLp;

    //使用按钮打的布局参数
    private RelativeLayout.LayoutParams btLp;

    //显示价格文字的布局参数
    private RelativeLayout.LayoutParams lpPrice;

    //Activity对象
    private Activity activity;

    public StDepotFoodAdapter(Activity activity, Context context, int layoutResId, @Nullable List<DepotInfo.DataBean.Type1Bean> data) {
        super(layoutResId, data);
        this.context = context;
        this.activity = activity;
        initLayoutParams(context);
    }

    /**
     * 适配屏幕的方法
     *
     * @param context
     */
    private void initLayoutParams(Context context) {
        screenWidth = ScreenUtils.getScreenWidth(context);
        //最外层的布局参数包含图片和按钮
        int rloutWidth = screenWidth * 134 / 498;
        int rloutHeight = rloutWidth * 232 / 134;
        lpOut = new RelativeLayout.LayoutParams(rloutWidth, rloutHeight);
        lpOut.addRule(RelativeLayout.CENTER_IN_PARENT);
        //配置包含ImageView和价格的整体布局参数
        int rlLvWidth = rloutWidth;
        int rllvHeight = rloutWidth * 162 / 134;
        rlLvLp = new RelativeLayout.LayoutParams(rlLvWidth, rllvHeight);
        //配置ImageView的布局参数
        int lvWidth = rloutWidth * 104 / 134;
        int lvHeight = rloutWidth * 84 / 134;
        lvLp = new RelativeLayout.LayoutParams(lvWidth, lvHeight);
        lvLp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        lvLp.topMargin = rloutWidth * 16 / 134;

        //配置Button的布局参数
        int btWidth = rloutWidth * 96 / 134;
        int btHeight = btWidth * 40 / 96;
        btLp = new RelativeLayout.LayoutParams(btWidth, btHeight);
        btLp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        btLp.topMargin = rloutWidth * 178 / 134;

//        lpPrice = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        lpPrice.topMargin = rloutWidth * 114 / 134;
//        lpPrice.addRule(RelativeLayout.CENTER_HORIZONTAL);
    }

    @Override
    protected void convert(BaseViewHolder helper, DepotInfo.DataBean.Type1Bean item) {
        //包含图片和按钮的外层相对布局
        RelativeLayout rlOut = helper.getView(R.id.rl_out);
        rlOut.setLayoutParams(lpOut);

        //只包含图片和价格的外层相对布局
        RelativeLayout rlLvOutSide = helper.getView(R.id.rl_lv_outside);
        rlLvOutSide.setLayoutParams(rlLvLp);

        //图片
        ImageView lvImg = helper.getView(R.id.lv_img);
        lvImg.setLayoutParams(lvLp);
        ImageUtil.displayImage(context, lvImg, item.getURL(),R.drawable.defaultimage);

        //按钮
        Button button = helper.getView(R.id.bt_buy);
        button.setLayoutParams(btLp);
        //根据服务器返回的状态来设置按钮需要显示的背景图
        if (((StudentDepotActivity) activity).getTotalMoney() < item.getPRICE()) {
            //用户的总余额<当前商品的价格,则按钮显示为灰色不可点击购买的状态
            button.setEnabled(false);
            button.setBackgroundResource(R.drawable.st_bug_normal);
        } else {
            button.setEnabled(true);
            button.setBackgroundResource(R.drawable.st_bug_select);
        }

        //文字
        TextView tvPrice = helper.getView(R.id.tv_price);
//        tvPrice.setLayoutParams(lpPrice);
        tvPrice.setText(item.getPRICE() + "");

        //使用的点击事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出已经使用的提示框
                shopMessagePop(item);
            }
        });
    }

    /**
     * 弹出是否购买的提示框
     *
     * @param item
     */
    private void shopMessagePop(DepotInfo.DataBean.Type1Bean item) {
        PopUpManager.showPop(context, R.layout.student_pop_buy, 0.3f, activity, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //标题
                TextView tvTile = view.findViewById(R.id.tv_title);
                tvTile.setText("确认购买" + item.getNAME() + "?");

                //商品图片
                ImageView lvShop = view.findViewById(R.id.lv_shop);
                ImageUtil.displayImage(context, lvShop, item.getURL(),R.drawable.defaultimage);

                //商品价格
                TextView tvPrice = view.findViewById(R.id.tv_price);
                tvPrice.setText(item.getPRICE() + "");

                //商品说明
                TextView tvGoods = view.findViewById(R.id.tv_goods);
                tvGoods.setText(item.getCONTENT());

                //关闭图片
                ImageView lvColse = view.findViewById(R.id.lv_close);
                lvColse.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });
                //确定按钮
                Button btBuy = view.findViewById(R.id.bt_buy);
                btBuy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        httpBuy(item);
                    }
                });
            }
        });
    }

    /**
     * 请求服务器进行商品购买
     *
     * @param item 商品
     */
    private void httpBuy(DepotInfo.DataBean.Type1Bean item) {


        String acc = SPUtil.getString(context, SpKeys.ACCOUNT);
        String token = SPUtil.getString(context, SpKeys.TOKEN1);

        Map<String, String> map = HttpUtils.getStudentMap();
        map.put("type", "7");
        map.put("boxitem", item.getROW_ID() + "");//商品ID
        map.put("boxtype", 1 + "");//美食1 服装2 道具3
        map.put("acc", acc);//账号
        map.put("role", "0");//角色
        map.put("apptoken", token);//token
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.DEPOT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    //解析返回服务器返回的JSON数据
                    ResultInfo info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    Log.i("test", "购买物品："+response);
                    if ("200".equals(info.state)) {
                        //购买成功
                        //通过EventBus更改Acitivity的总金币余额
                        EventBus.getDefault().post(new BusInfo(item.getPRICE()));
                        UiUtils.Toast("购买成功", false);
                        //通知适配器刷新
                        notifyDataSetChanged();
                        PopUpManager.dismiss();
                    } else if("201002".equals(info.state)){
                        //购买失败
                        UiUtils.Toast("已达到购买次数上限", false);
                    }else{
                        Log.i("test", "返回错误码"+info.state);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "解析服务器返回数据异常");
                }

            }
        });


    }
}
